package iPod;

import java.io.*;
import java.util.ArrayList;

import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;

public class PlayCountList {
	// Temporary access variable
	protected byte item[] = new byte[4];
	protected long startPos = 0;
	
	// Chunk data
	protected String typeID = null;
	protected int headerSize = 0;
	protected int entrySize = 0;
	protected int numEntries = 0;
	
	protected ArrayList<PlayCountItem> playcountlist = new ArrayList<PlayCountItem>();
   
    // chunk access functions
    public void load(RandomAccessFile in) throws Exception
    {
    	// Load header information
    	loadRecord(in);
    	
    	// read the children
    	loadChildren(in);   	    
    }
    
    public void loadRecord(RandomAccessFile in) throws Exception
    {
    	// Mark the beginning of this block (so we can reset)
    	startPos = in.getFilePointer();
    	
    	// read the header
    	loadHeader(in); 
    	
    	// jump back to the beginning
    	in.seek(startPos);
    }
    
    public void loadHeader(RandomAccessFile in) throws Exception
    {      	
    	// Read the typeID
    	in.read(item);
    	typeID = new String(item);
    	if (!"mhdp".equalsIgnoreCase(typeID))
    		throw new Exception("Unexpected typeID read - " + typeID);
    	
    	// read the size of the header
    	in.read(item);
    	headerSize = DataUtils.littleEndianToInt(item);
    	
    	// read the size of each entry
    	in.read(item);
    	entrySize = DataUtils.littleEndianToInt(item);
    	
    	// read the number of entries
    	in.read(item);
    	numEntries = DataUtils.littleEndianToInt(item);
    }
    
    public void loadChildren(RandomAccessFile in) throws Exception
    {
    	in.seek(startPos + headerSize);    	
    	
    	for (int index = 0; index < numEntries; ++index)
    	{
    		in.seek(startPos + headerSize + index * entrySize);
    		
			// Read all the chunks possible in the file
			PlayCountItem item = new PlayCountItem();
			item.loadRecord(in);			
			
			playcountlist.add(item);
		}
    }

	public ArrayList<PlayCountItem> getPlaycountlist() {
		return playcountlist;
	}
}
